package codeRandomThoughts.Test131分割回文串;

import java.util.ArrayList;
import java.util.List;

public class Solution {
    List<String> path = new ArrayList<>();
    List<List<String>> result = new ArrayList<>();

    public List<List<String>> partition(String s) {
        int startIndex = 0;
        backtracking(s, startIndex);
        return result;
    }

    public void backtracking(String s, int startIndex) {
        //终止条件
        if (startIndex >= s.length()) {
            result.add(new ArrayList<>(path));
            return;
        }

        //单层搜索逻辑
        for (int i = startIndex; i < s.length(); i++) {
            //检查被分割的子串是不是回文串
            //子串起始位置为startIndex,终止位置为i
            if (isPalindrome(s, startIndex, i)) {
                path.add(s.substring(startIndex, i + 1));
            } else {
                continue;
            }
            backtracking(s, i + 1);
            path.remove(path.size() - 1);
        }
    }

    public boolean isPalindrome(String s, int start, int end) {
        while (start < end) {
            if (s.charAt(start) != s.charAt(end)) {
                return false;
            }
            start++;
            end--;
        }
        return true;
    }
}
